package com.lottry.acra;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import org.acra.ACRAConstants;
import org.acra.ReportField;
import org.acra.collector.CrashReportData;
import org.acra.model.Element;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class LocalReportSender implements ReportSender
{
    private FileWriter crashReportWriter = null;

    public LocalReportSender(Context ctx) {
        File logFile = new File(Environment.getExternalStorageDirectory(), "BasicCrash.log");

        try {
            crashReportWriter = new FileWriter(logFile, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private boolean isNull(String aString) {
        return aString == null || ACRAConstants.NULL_VALUE.equals(aString);
    }

    private Map<String, String> remap(CrashReportData report) {

        ReportField[] fields = ACRAConstants.DEFAULT_MAIL_REPORT_FIELDS;

        final Map<String, String> finalReport = new HashMap<>(
                report.size());
        for (ReportField field : fields) {
            Element value = report.get(field);
            if (value != null)
            {
                finalReport.put(field.toString(), TextUtils.join("\n\t", value.flatten()));
            }
        }
        return finalReport;
    }

    @Override
    public void send(@NonNull Context context, @NonNull CrashReportData crashReportData) throws ReportSenderException {
        final Map<String, String> finalReport = remap(crashReportData);

        if (crashReportWriter != null)
        {
            try
            {
                BufferedWriter buf = new BufferedWriter(crashReportWriter);

                Set<Map.Entry<String, String>> set = finalReport.entrySet();
                Iterator<Map.Entry<String, String>> i = set.iterator();

                while (i.hasNext())
                {
                    Map.Entry<String, String> me = i.next();
                    buf.append("[" + me.getKey() + "]=" + me.getValue() + "\n");
                }

                buf.flush();
                buf.close();
            }
            catch (IOException e)
            {
                Log.e("TAG", "IO ERROR", e);
            }
        }
    }
}
